package socket2;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;


@SuppressWarnings("serial")
public class SocketServidor extends JFrame implements ActionListener{
	
	ServerSocket servidor = null;
	Socket cliente = null;
	BufferedReader entrada;
	PrintWriter salida;
	String lineaLeida;
	int puerto;
	
	JButton button = null;
	JLabel label = new JLabel("Texto recibido.");
	Panel panel = null;
	JTextArea tArea= new JTextArea();
	
	
	public SocketServidor(int puerto){
		this.puerto = puerto;
		
		cargarGraficos();
		
		
		setTitle("ProgramaServidor");
		WindowListener listener = new WindowAdapter(){
			public void windowClosing(WindowEvent event){
				System.exit(0);
			}
		};
		addWindowListener(listener);
		pack();
		setVisible(true);
		//escuchar(puerto);
		
	}


	private void cargarGraficos() {
		button = new JButton("Recibir");
	    button.addActionListener(this);;
		
		panel = new Panel();
		panel.setLayout(new BorderLayout());
		panel.setMinimumSize(new Dimension(100, 150));
		getContentPane().add(panel);
		panel.add("North", tArea);
		panel.add("Center", label);
		panel.add("South", button );
	}


	private void escuchar(int puerto) {
		try {
			servidor = new ServerSocket(puerto);
		} catch (IOException e) {
			System.out.println("Error al crear un ServerSocket en el puerto: " + puerto + ".");
			System.exit(-1);
		}
		try {
			cliente = servidor.accept();
		} catch (IOException e) {
			System.out.println("Error al aceptar un cliente.");
			System.exit(-1);
		}
		try {
			entrada = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
		} catch (IOException e) {
			System.out.println("Error al referenciar al cliente.");
			System.exit(-1);
		}
	}


	public void actionPerformed(ActionEvent e) {
		
		Object origen = e.getSource();
		
		if(origen == button){
			tArea.setText(lineaLeida);
		}
	}
	public static void main(String[] args) {
		SocketServidor serv= new SocketServidor(3333);
		serv.escuchar(3333);
	}
}

